import { getOneCategory } from "@/api/category";
import { topCategories } from "@/api/constants";

const category = {
  namespaced: true,
  state() {
    return {
      list: topCategories.map((name) => ({ name })),
    };
  },
  mutations: {
    // 保存一级分类数据到vuex
    setOneCategory(state, payload) {
      state.list = payload;
    },
    // 显示二级分类
    open(state, payload) {
      let list = state.list.find((item) => item.id === payload);
      list.open = true;
    },
    close(state, payload) {
      let list = state.list.find((item) => item.id === payload);
      list.open = false;
    },
  },
  actions: {
    // 异步获取一级分类数据
    getOneCategories({ commit }) {
      getOneCategory().then((data) => {
        data.result.forEach((item) => (item.open = false));
        commit("setOneCategory", data.result);
      });
    },
  },
};
export default category;
